<template>
  <div class="system-info">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>我的申请</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
              <!-- 流程名称 -->
              <el-form-item label="流程名称">
                <el-select
                  v-model="formInline.flowId"
                  filterable
                  auto-complete="off"
                  placeholder="请选择"
                  style="width:150px;"
                >
                  <el-option label="无" value></el-option>
                  <!-- 循环所有角色 角色名称 角色ID -->
                  <el-option
                    v-for="(item,index) in flowList"
                    :key="index"
                    :label="item.flowName"
                    :value="item.flowId"
                  ></el-option>
              </el-select>
            </el-form-item>
            <!-- 申请日期 -->
            <el-form-item label="申请日期">
              <el-date-picker v-model="formInline.flowOriginatorTime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <!-- 搜索 -->
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮 是否授权显示-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          <!-- 发起流程 -->
          <el-button
            v-if="btnAdd"
            type="success"
            size="medium"
            icon="el-icon-document-add"
            @click="drawer = true"
          >发起流程</el-button>
        </el-row>
        <!-- 数据列表 -->
        <el-table
          :data="menusData"
          border
          style="width: 100%"
          height="395"
          ref="menusData"
        >
          <!-- 流程名称 -->
          <el-table-column :show-overflow-tooltip="true" prop="flowCode" label="流程编号" width="220"></el-table-column>
          <!-- 当前环节 -->
          <el-table-column label="当前环节" align="center" width="200">
            <template slot-scope="scope">{{ scope.row.flowCurrentNode | getNode(scope.row) }}</template>
          </el-table-column>
          <!-- 审批人 -->
          <el-table-column label="审批人" align="center" width="100">
            <template slot-scope="scope">{{ scope.row.flowCurrentUser | getName(users) }}</template>
          </el-table-column>
          <!-- 工单状态 -->
          <el-table-column align="center" label="状态" width="150">
            <template slot-scope="scope">
              <!-- 工单状态 1.暂存草稿 2.已发起 3.正常处理 4.处理完成 5.驳回申请 -->
              <span v-if="scope.row.status === 1">
                暂存草稿
              </span>
              <span v-if="scope.row.status === 2">
                已发起
              </span>
              <span v-if="scope.row.status === 3">
                正常处理
              </span>
              <span v-if="scope.row.status === 4">
                处理完成
              </span>
              <span v-if="scope.row.status === 5">
                驳回申请
              </span>
            </template>
          </el-table-column>
          <!-- 申请日期 时间格式过滤 -->
          <el-table-column label="申请日期" align="center" width="120">
            <template slot-scope="scope">{{ scope.row.flowOriginatorTime | filterTime }}</template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column
            label="管理"
            fixed="right"
            align="center"
            width="500"
            v-if="[btnDel,btnEdit].indexOf(true) > -1"
          >
            <template slot-scope="scope">
              <!-- 立即申请 -->
              <el-button
                type="success"
                size="mini"
                @click="initiate(scope.row)"
                v-if="scope.row.status === 1"
              >立即申请</el-button>
              <!-- 重新申请 -->
              <el-button
                type="warning"
                size="mini"
                @click="reapply(scope.row)"
                v-if="scope.row.status === 5"
              >重新申请</el-button>
              <!-- 修改编辑 -->
              <el-button
                type="primary"
                size="mini"
                @click="editHandle(scope.row)"
                v-if="scope.row.status === 1 || scope.row.status === 5"
              >修改编辑</el-button>
              <!-- 表单数据 -->
              <el-button size="mini" @click="formDatas(scope.row)" v-if="scope.row.status !== 1">表单数据</el-button>
              <!-- 审批历史 -->
              <el-button type="info" size="mini" @click="history(scope.row)" v-if="scope.row.status !== 1">审批历史</el-button>
              <!-- 取消申请 -->
              <el-button
                type="danger"
                size="mini"
                @click="cancel(scope.row)"
                v-if="scope.row.status !== 1 && scope.row.status !== 4"
              >取消申请</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
      <el-drawer
        title="选择流程"
        :visible.sync="drawer"
        close-on-press-escape
        :with-header="false">
        <flow-list @cls="getCls"></flow-list>
      </el-drawer>
      <el-dialog title="流程图" :visible.sync="modalVisible" width="600px">
        <div class="flowLog">
          <el-table
            :data="historyLog"
            border
            style="width: 100%">
            <!-- 处理人 -->
            <el-table-column label="处理人" align="center" width="100">
              <template slot-scope="scope">{{ scope.row.createUserId | getName(users) }}</template>
            </el-table-column>
            <!-- 处理日期 时间格式过滤 -->
            <el-table-column label="处理日期" align="center" width="120">
              <template slot-scope="scope">{{ scope.row.createTime | filterTime }}</template>
            </el-table-column>
            <el-table-column align="center" label="结果" width="60">
              <template slot-scope="scope">
                <!-- 处理结果 1.发起 2.通过 3.驳回 4.取消 -->
                <span v-if="scope.row.result === 1">
                  发起
                </span>
                <span v-if="scope.row.result === 2">
                  通过
                </span>
                <span v-if="scope.row.result === 3">
                  驳回
                </span>
                <span v-if="scope.row.result === 4">
                  取消
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="note"
              label="审批说明">
            </el-table-column>
          </el-table>
        </div>
        <node-data ref="nodeFlow" :nodeData="nodeData"></node-data>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入时间格式化插件
import moment from 'moment';
// 节点展示组件
import NodeData from '@/components/NodeData';
// 引入流程列表组件
import flowList from '@/components/FlowList';

export default {
  components: {
    flowList,
    NodeData
  },
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 实例创建后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取所有流程模型数据
    this.getFlowList();

    // 获取所有用户数据
    this.getAllUsers();

    // 加载分页数据
    this.getmenusDataByPage();
  },

  // 过滤器
  filters: {
    // 时间显示过滤
    filterTime (value) {
      return moment(value).format('YYYY-MM-DD');
    },
    // 节点过滤
    getNode (value, datas) {
      if (datas.flowJson !== undefined) {
        let lists = JSON.parse(datas.flowJson);
        for (let i = 0; i < lists.nodes.length; i++) {
          if (lists.nodes[i].id === value) {
            return lists.nodes[i].label;
          }
        }
      }
    },
    // 审批人过滤
    getName (value, params) {
      for (let i = 0; i < params.length; i++) {
        if (params[i].userId === value) {
          return params[i].userName;
        }
      }
    }
  },

  // 当前页面数据
  data () {
    return {

      // 流程菜单是否显示
      drawer: false,
      // 屏蔽重复提交
      isSubmit: false,
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 获取公司列表
      lv1: [],
      // 获取部门列表
      lv2: [],

      // 过滤器匹配
      dept: [],

      // 当前用户数据
      users: '',

      // 搜索条件
      formInline: {
        // 流程模型ID
        flowId: '',
        // 工单申请时间
        flowOriginatorTime: ''
      },

      // 流程图预览数据
      nodeData: {},
      // 流程历史是否显示
      modalVisible: false,
      // 所有流程信息
      flowList: [],
      // 审批历史数据
      historyLog: [],
      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20
    };
  },
  methods: {

    // 获取所有用户
    getAllUsers () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.users = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取所有流程数据
    getFlowList: function () {
      this.$http.raw('api/findAllFlow').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.flowList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取流程模型组件数据
    getCls (data) {
      this.drawer = data;
    },

    // 按钮级授权
    authorization (data) {
      for (let i in data) {
        if (data['sel'] === 0) {
          this.btnSel = false;
        }
        if (data['add'] === 0) {
          this.btnAdd = false;
        }
        if (data['del'] === 0) {
          this.btnDel = false;
        }
        if (data['upload'] === 0) {
          this.btnUpload = false;
        }
        if (data['down'] === 0) {
          this.btnDown = false;
        }
        if (data['edit'] === 0) {
          this.btnEdit = false;
        }
        return i;
      }
    },

    // 发起申请
    initiate: function (row) {
      // 初始数据源
      let nodeDB = row;
      // 获取节点数据JSON
      let list = JSON.parse(nodeDB.flowJson);
      // 获取当前登录人
      let flowUser = this.$store.state.userinfo.userId;
      // 节点列表
      let nodes = list.nodes;
      // 发起节点的ID
      let setUpNodeId = '';

      // 判断发起人是否在审批节点中
      for (let i = 0; i < nodes.length; i++) {
        for (let j = 0; j < nodes[i].users.length; j++) {
          if (nodes[i].users[j] === flowUser) {
            setUpNodeId = nodes[i].id;
          } else {
            if (nodes[i].type === '开始') {
              setUpNodeId = nodes[i].id;
            }
          }
        }
      }

      // 审批人
      let users = [];
      // 根据发起节点ID查找下一步审批节点的审批人、审批节点ID
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          list.nodes.map(key => {
            if (item.target === key.id) {
              users.push(key.users);
            }
          });
        }
      });

      // 下一步审批节点
      let nextNode = [];
      // 根据发起节点ID查找下一步审批节点ID
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          nextNode.push(item.target);
        }
      });

      // 判断操作的下一节点是否为结束节点
      for (let m = 0; m < nodes.length; m++) {
        if (nextNode.length === 1) {
          if (nextNode[0] === nodes[m].id) {
            if (nodes[m].type !== '结束') {
              let params = {
                // 工单编号
                flowCode: row.flowCode,
                flowOriginator: this.$store.state.userinfo.userId,

                flowCurrentNode: nextNode.toString(),
                flowCurrentUser: users[0].toString(),
                // 工单优先级
                flowPriority: row.flowPriority,
                // 消息推送
                msgPush: row.msgPush,
                flowNode: setUpNodeId,
                status: 2,
                result: '已发起',
                note: '发起申请',
                workResult: 1
              };
              this.$http.raw('api/updateOrderStatus', params).then(res => {
                let { code } = res;
                // 判断Code状态
                if (code === 0) {
                  this.$message({
                    message: '发起流程成功！',
                    type: 'success'
                  });
                  this.getmenusDataByPage();
                }
              }).catch(err => {
                if (err === undefined) {
                  this.$message({
                    message: '服务器响应异常！',
                    type: 'error'
                  });
                  return false;
                }
              });
            } else {
              let params = {
                // 工单编号
                flowCode: row.flowCode,
                flowOriginator: this.$store.state.userinfo.userId,

                flowCurrentNode: nextNode.toString(),
                flowCurrentUser: users[0].toString(),
                // 工单优先级
                flowPriority: row.flowPriority,
                // 消息推送
                msgPush: row.msgPush,
                flowNode: setUpNodeId,
                status: 4,
                result: '已发起并通过审批！',
                note: '发起申请并通过审批！',
                workResult: 2
              };

              this.$http.raw('api/updateOrderStatus', params).then(res => {
                let { code } = res;
                // 判断Code状态
                if (code === 0) {
                  this.$message({
                    message: '发起流程成功！',
                    type: 'success'
                  });
                  this.getmenusDataByPage();
                }
              }).catch(err => {
                if (err === undefined) {
                  this.$message({
                    message: '服务器响应异常！',
                    type: 'error'
                  });
                  return false;
                }
              });
            }
          }
        }
      }
    },

    // 重新申请
    reapply: function (row) {
      // 初始数据源
      let list = JSON.parse(row.flowJson);

      // 获取发起节点的ID
      let setUpNodeId = list.nodes[0].id;
      // 根据发起节点ID查找下一步审批节点的审批人、审批节点ID
      let users = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          list.nodes.map(key => {
            if (item.target === key.id) {
              users.push(key.users);
            }
          });
        }
      });
      // 根据发起节点ID查找下一步审批节点ID
      let nextNode = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          nextNode.push(item.target);
        }
      });

      let params = {
        // 工单编号
        flowCode: row.flowCode,
        flowOriginator: this.$store.state.userinfo.userId,

        flowCurrentNode: nextNode.toString(),
        flowCurrentUser: users[0].toString(),
        // 工单优先级
        flowPriority: row.flowPriority,
        // 消息推送
        msgPush: row.msgPush,
        flowNode: row.flowCurrentNode,
        status: 2,
        result: '已发起',
        note: '重新申请',
        workResult: 1
      };

      this.$http.raw('api/updateOrderStatus', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '发起流程成功！',
            type: 'success'
          });
          this.getmenusDataByPage();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 取消申请
    cancel: function (row) {
      // 初始数据源
      let list = JSON.parse(row.flowJson);

      // 获取发起节点的ID
      let setUpNodeId = list.nodes[0].id;
      // 根据发起节点ID查找下一步审批节点的审批人、审批节点ID
      let users = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          list.nodes.map(key => {
            if (item.target === key.id) {
              users.push(key.users);
            }
          });
        }
      });
      // 根据发起节点ID查找下一步审批节点ID
      let nextNode = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          nextNode.push(item.target);
        }
      });

      let params = {
        // 工单编号
        flowCode: row.flowCode,
        // 发起人
        flowOriginator: '',
        // 当前审批节点
        flowCurrentNode: setUpNodeId,
        // 当前审批人
        flowCurrentUser: this.$store.state.userinfo.userId,
        // 工单状态
        status: 1,
        // 工单优先级
        flowPriority: row.flowPriority,
        // 消息推送
        msgPush: row.msgPush,
        // 处理结果
        result: '已取消',
        // 审批历史-审批节点
        flowNode: setUpNodeId,
        // 审批历史-审批意见
        note: '取消申请',
        // 审批历史-审批结果
        workResult: 4
      };
      this.$http.raw('api/updateOrderStatus', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '已取消申请！',
            type: 'success'
          });
          this.getmenusDataByPage();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 审批历史
    history: function (row) {
      let params = {
        flowCode: row.flowCode
      };
      this.$http.post('api/findWorkResultList', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          let currentNode = row.flowCurrentNode;
          let flowJson = JSON.parse(row.flowJson);
          flowJson.nodes.map(item => {
            if (item.id === currentNode) {
              item.color = '#FF0000';
            }
          });
          // 流程图预览
          this.modalVisible = true;
          this.nodeData = flowJson;
          this.historyLog = res.datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 显示编辑界面
    editHandle: function (row) {
      let params = {
        flowId: row.flowId
      };
      this.$http.post('api/findFlowRouter', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$router.push({
            path: res.datas,
            query: {
              node: 1,
              datas: row
            }
          });
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 表单数据
    formDatas: function (row) {
      let params = {
        flowId: row.flowId
      };
      this.$http.post('api/findFlowRouter', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$router.push({
            path: res.datas,
            query: {
              node: 2,
              datas: row
            }
          });
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 显示新增界面
    addHandle: function () {
      // 弹出窗类型
      this.dialogStatus = 'create';
      // 弹出窗显示状态
      this.dialogFormVisible = true;
      // 重置新增界面默认数据
      this.editForm = {
        parentId: '0',
        compId: '',
        deptId: '',
        deptName: '',
        note: ''
      };
    },

    // 查询
    selHandle: function () {
      // 收集请求数据
      let params = {
        flowId: this.formInline.flowId === null ? '' : this.formInline.flowId,
        originatorTime: moment(this.formInline.flowOriginatorTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(this.formInline.flowOriginatorTime).format('YYYY-MM-DD'),
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      // 根据公司ID请求对应分页数据结果
      this.$http.raw('api/findOrderByFlowIdAndTime', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 刷新页面数据
    getmenusDataByPage () {
      // 收集请求参数
      let params = {
        flowId: '',
        originatorTime: '',
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      this.$http.raw('api/findOrderByFlowIdAndTime', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    }
  }
};
</script>

<style lang='scss'>
@import './index.scss';
</style>
